<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="生产计划单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入生产计划单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="客户" name="client">
						<uni-data-select mode="underline" placeholder="请选择客户" v-model="form.client" :localdata="client_list"
							:clear="false" :disabled="pageInfo.type == 'edit'" />
					</uni-forms-item>
					<uni-forms-item label="交货日期" name="delivery_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择交货日期" :clear-icon="false"
								v-model="form.delivery_date" @show="car_popup_Show = false" @maskClick="car_popup_Show = true"
								@change="car_popup_Show = true" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="预计完成日期" name="finish_date">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择预计完成日期" :clear-icon="false"
								v-model="form.finish_date" @show="car_popup_Show = false" @maskClick="car_popup_Show = true"
								@change="car_popup_Show = true" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" :animation="cartShakeAnim" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${pro_list.length}`"></u--text>
					<u--text type="info" :text="`半成品数量：${bom_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(pro_list.length) || Boolean(bom_list.length) }"
					v-show="car_popupShow" @click.stop="save">提交计划
				</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="选择生产" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="'生产'" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false" v-model="car_list"
					@query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<up-tabs :list="list" lineWidth="60" @change="tab_change" :scrollable="false"
								style="border-bottom: 1rpx solid #e9e9e9;"></up-tabs>
							<up-tabs :list="list2" lineWidth="20" @change="tab_change2" :scrollable="false"
								style="border-bottom: 1rpx solid #e9e9e9;" v-show="uTab1 == '1'"></up-tabs>
							<u-button type="primary" size="small" v-show="uTab1 == '1'"
								style="display: inline-flex;width: auto; margin: 15rpx;" :text="uTab2 == '1' ? '选择产品' : '选择半成品'"
								@click="sect_popupShow = true"></u-button>
						</view>
					</template>
					<uni-card v-for="(item, index) in car_list" :key="index" margin="5px" spacing="0">
						<template v-slot:title>
							<uni-list>
								<uni-list-item :title="item.name" thumbSize="lg">
									<template v-slot:footer>
										<view v-show="uTab1 == '1'">
											<up-icon name="trash" color="red" size="28" @click="removeTransfer(index)" />
										</view>
									</template>
								</uni-list-item>
							</uni-list>
						</template>
						<view v-show="uTab1 == '1'">
							<view class="ctent">规格：{{ item.specification }}</view>
							<view class="ctent">BOM量：{{ item.bom_num }}</view>
							<view class="con">
								<view class="ctent" style="flex: none;">生产数量：</view>
								<custom-num-box v-model="item.num" :min="1" @change="numChange($event, item)"></custom-num-box>
							</view>
						</view>
						<view v-show="uTab1 == '2'">
							<view class="con">
								<view class="ctent">单次工价(元)：{{ item.price }}</view>
								<view class="ctent">单次完成时间(秒)：{{ item.finish_m }}</view>
							</view>
							<view style="background-color: #f2f5f9;">
								<uni-card v-for="val in item.children" margin="5px" spacing="0" :title="val.name">
									<view class="ctent">单次工价(元)：{{ val.price }}</view>
									<view class="ctent">单次完成时间(秒)：{{ val.finish_m }}</view>
									<view class="con">
										<view class="ctent" style="flex: none;">工序数量：</view>
										<custom-num-box v-model="val.now_num" :min="1"></custom-num-box>
									</view>
									<view class="ctent">工序要求：<view class="white-text">{{ val.require }}</view>
									</view>
								</uni-card>
							</view>
						</view>
					</uni-card>
					<template #bottom>
						<view class="zhanwei"></view>
					</template>
				</z-paging>
				<custom-popup :popupShow="sect_popupShow" mode="center" :title="uTab2 == '1' ? '选择产品' : '选择半成品'" width="96%"
					height="60%" class="popup-custom" @close="close_sect" :closeOnClickOverlay="false">
					<FlyBall ref="flyBall" />
					<z-paging v-if="sect_popupShow" ref="paging" :fixed="false" v-model="sect_list" @query="queryList_sect">
						<template #top>
							<view class="zpagin_top">
								<view class="search">
									<custom-search v-model="searchVal" @search="refreshList"
										:placeholder="uTab2 == '1' ? '请输入产品名称或编号' : '请输入半成品名称或编号'" />
								</view>
							</view>
						</template>
						<uni-card v-for="(item, index) in sect_list" :key="item.id" margin="5px" spacing="0">
							<template v-slot:title>
								<uni-list>
									<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
										<template v-slot:footer>
											<view :id="`goods-btn${index}`">
												<u-button type="primary" size="small" shape="circle" text="添加" @click="hanldAddWar(index, item)"
													:disabled="isInTransfer(item.id)"></u-button>
											</view>
										</template>
									</uni-list-item>
								</uni-list>
							</template>
							<view class="ctent">规格：{{ item.specification }}</view>
							<view class="ctent">成本：{{ item.all_cost }}</view>
						</uni-card>
					</z-paging>
				</custom-popup>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import pPlanApi from '../../../api/production/p_plan'
import { generateCode, debounce, shakeCartIcon, getRectDom } from '@/utils/index.js';
import FlyBall from '@/components/flyBall'
//页面标题
const pageInfo = reactive({
	navbarTitle: '生产计划',
	type: '',
	edit_id: null,
});
onLoad(option => {
	get_client_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('PP')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('PP')
	}
}

const list = [
	{ name: '生产产品(步骤一)', status: "1" },
	{ name: '生产工序(步骤二)', status: '2' }
]
const list2 = [
	{ name: '产品', status: "1" },
	{ name: '半成品', status: '2' }
]

const uTab1 = ref('1')
const uTab2 = ref('1')

const refForm = ref(null)
const form = reactive({
	code: '',
	client: null,
	delivery_date: '',
	finish_date: '',
	desc: ''
})
const fields = Object.keys(form)
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入报价单号' }] },
	delivery_date: { rules: [{ required: true, errorMessage: '请选择交货日期' }] },
}

function get_detail(id) {
	pPlanApi.production_plan_detail(id).then(data => {
		const record = uni.$lodash.pick(data, fields)
		Object.assign(form, record)
		for (let i = 0; i < data.plan_products.length; i++) {
			let bom_lists = null
			if (data.plan_products[i].p_type === 2) {
				bom_lists = data.plan_products[i].product.children
			} else {
				bom_lists = JSON.parse(data.plan_products[i].product.bom_info)['bom_info']
			}
			const bom_num = bom_lists.reduce((total, item) => {
				return total + (Number(item.num) || 0)
			}, 0)
			const info = {
				id: data.plan_products[i].product.id,
				code: data.plan_products[i].product.code,
				name: data.plan_products[i].product.name,
				specification: data.plan_products[i].product.specification,
				bom_num: bom_num,
				bom_info: data.plan_products[i].product.bom_info,
				unit_main: data.plan_products[i].product.unit_main,
				num: data.plan_products[i].num,
				f_num: bom_num * data.plan_products[i].num,
				process_data: data.plan_products[i].product.process_data
			}
			if (data.plan_products[i].p_type === 2) {
				bom_list.value.push(info)
			} else {
				pro_list.value.push(info)
			}

			const plan_products_process = data.plan_products[i].plan_products_process
			let all_price = 0
			let all_finish_m = 0
			const children_list = []
			for (let j = 0; j < plan_products_process.length; j++) {
				all_price += parseFloat(plan_products_process[j].process.price)
				all_finish_m += parseFloat(plan_products_process[j].process.finish_m)

				children_list.push({
					id: plan_products_process[j].process.id,
					id_info: 'process_' + plan_products_process[j].process.id,
					type: 'process',
					name: plan_products_process[j].process.name,
					price: plan_products_process[j].process.price,
					finish_m: plan_products_process[j].process.finish_m,
					now_num: plan_products_process[j].num,
					require: plan_products_process[j].process.require
				})
			}
			if (data.plan_products[i].p_type === 2) {
				process_h.value.push({
					id: data.plan_products[i].product.id,
					code: data.plan_products[i].product.code,
					id_info: 'bom_' + data.plan_products[i].product.id,
					type: 'bom',
					name: data.plan_products[i].product.name,
					price: all_price,
					finish_m: all_finish_m,
					now_num: '-', // 总体 now_num 不在这层处理
					require: '-',
					children: children_list
				})
			} else {
				process_p.value.push({
					id: data.plan_products[i].product.id,
					code: data.plan_products[i].product.code,
					id_info: 'product_' + data.plan_products[i].product.id,
					type: 'product',
					name: data.plan_products[i].product.name,
					price: all_price,
					finish_m: all_finish_m,
					now_num: '-', // 总体 now_num 不在这层处理
					require: '-',
					children: children_list
				})
			}
			merge_process_list()
		}
	})
}

const process_list = ref([])
const process_h = ref([])
const process_p = ref([])
function merge_process_list() {
	process_list.value = [...process_h.value, ...process_p.value]
}

const searchVal = ref('')
const paging = ref(null)
const sect_popupShow = ref(false)
const sect_list = ref([])
function queryList_sect(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		if_open: 1,
		search: searchVal.value,
	}
	if (uTab2.value == '1') {
		pPlanApi.get_product(params).then((res) => {
			paging.value.complete(res.results);
		})
	}
	if (uTab2.value == '2') {
		params.style = '2,3'
		pPlanApi.get_bom(params).then((res) => {
			paging.value.complete(res.results);
		})
	}
}
function refreshList() {
	paging.value.reload();
}

const paging_car = ref(null)
const bom_list = ref([])
const pro_list = ref([])
function close_sect() {
	sect_popupShow.value = false
	if (uTab2.value == '1') {
		paging_car.value.complete(pro_list.value);
	}
	if (uTab2.value == '2') {
		paging_car.value.complete(bom_list.value);
	}
}

function tab_change(v) {
	uTab1.value = v.status
	paging_car.value.reload();
}
function tab_change2(v) {
	uTab2.value = v.status
	paging_car.value.reload();
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		params.process_list = process_list.value
		params.product_info = {
			product_list: pro_list.value,
			bom_list: bom_list.value
		}
		if (pageInfo.type == 'add') {
			pPlanApi.post_production_plan(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			pPlanApi.patch_production_plan(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

const car_list = ref([])
function queryList_car() {
	if (uTab1.value == '1') {
		if (uTab2.value == '1') {
			paging_car.value.complete(pro_list.value);
		}
		if (uTab2.value == '2') {
			paging_car.value.complete(bom_list.value);
		}
	}
	if (uTab1.value == '2') {
		paging_car.value.complete(process_list.value);
	}
}


const client_list = ref([])
function get_client_list() {
	const params = { page: 1, page_size: 99999 };
	pPlanApi.get_client(params).then(res => {
		client_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
}

function isInTransfer(id) {
	if (uTab2.value == '1') {
		return pro_list.value.some(item => item.id === id)
	}
	if (uTab2.value == '2') {
		return bom_list.value.some(item => item.id === id)
	}
}
function removeTransfer(index) {
	if (uTab2 == '1') {
		pro_list.value.splice(index, 1)
		paging_car.value.complete(pro_list.value);
		get_table_data(pro_list.value)
	}
	if (uTab2 == '2') {
		bom_list.value.splice(index, 1)
		paging_car.value.complete(bom_list.value);
		get_table_data_h(bom_list.value)
	}
	merge_process_list()
}

const cartShakeAnim = ref()
const flyBall = ref({});
const { proxy } = getCurrentInstance()
async function hanldAddWar(index, item) {
	const dataIndex = `#goods-btn${index}`
	const startRect = await getRectDom(dataIndex, proxy);
	const endRect = await getRectDom('.cartIcon', proxy);
	//小球动画完成回调函数
	flyBall.value.launch(startRect, endRect, () => {
		if (isInTransfer(item.id)) return;
		if (uTab2.value == '1') {
			const bom_list = JSON.parse(item.bom_info)
			const obj = {
				...item,
				bom_num: bom_list.bom_info.reduce((total, item) => {
					return total + (Number(item.num) || 0)
				}, 0),
				num: 1,
				f_num: 0,
				p_type: 2
			}
			pro_list.value.push(obj)
			get_table_data(pro_list.value)
		}
		if (uTab2.value == '2') {
			const obj = {
				...item,
				bom_num: item.children.reduce((total, item) => {
					return total + (Number(item.num) || 0)
				}, 0),
				num: 1,
				f_num: 0,
				p_type: 1
			}
			bom_list.value.push(obj)
			get_table_data_h(bom_list.value)
		}
		cartShakeAnim.value = shakeCartIcon()
	})
}

const car_popupShow = ref(false)
function get_table_data_h(tableDataH) {
	const nowNumMap = new Map()
	for (const item of form.process_list || []) {
		const bomId = item.id
		for (const child of item.children || []) {
			const key = `${bomId}_${child.id}`
			nowNumMap.set(key, child.now_num)
		}
	}
	// 重新构建 process_list，但尽量复用原来的 now_num
	process_h.value = []
	for (const bom of tableDataH) {
		const children_list = []
		const process_data = bom.process_data || []
		let all_price = 0
		let all_finish_m = 0

		for (const process of process_data) {
			all_price += parseFloat(process.price)
			all_finish_m += parseFloat(process.finish_m)
			const key = `${bom.id}_${process.id}`
			const saved_now_num = nowNumMap.get(key) || 1

			children_list.push({
				id: process.id,
				id_info: 'process_' + process.id,
				type: 'process',
				p_type: 'bom',
				name: process.name,
				price: process.price,
				finish_m: process.finish_m,
				now_num: saved_now_num,
				require: process.require
			})
		}
		process_h.value.push({
			id: bom.id,
			code: bom.code,
			id_info: 'bom_' + bom.id,
			type: 'bom',
			name: bom.name,
			price: all_price,
			finish_m: all_finish_m,
			now_num: '-', // 总体 now_num 不在这层处理
			require: '-',
			children: children_list
		})
	}
	merge_process_list()
}
function get_table_data(tableData) {
	// 缓存旧数据中的 now_num
	const nowNumMap = new Map()
	for (const item of form.process_list || []) {
		const productId = item.id
		for (const child of item.children || []) {
			const key = `${productId}_${child.id}` // 用 product_id + process_id 作为 key
			nowNumMap.set(key, child.now_num)
		}
	}

	// 重新构建 process_list，但尽量复用原来的 now_num
	process_p.value = []
	for (const product of tableData) {
		const children_list = []
		const process_data = product.process_data || []
		let all_price = 0
		let all_finish_m = 0

		for (const process of process_data) {
			all_price += parseFloat(process.price)
			all_finish_m += parseFloat(process.finish_m)
			const key = `${product.id}_${process.id}`
			const saved_now_num = nowNumMap.get(key) || 1

			children_list.push({
				id: process.id,
				id_info: 'process_' + process.id,
				type: 'process',
				p_type: 'product',
				name: process.name,
				price: process.price,
				finish_m: process.finish_m,
				now_num: saved_now_num,
				require: process.require
			})
		}
		process_p.value.push({
			id: product.id,
			id_info: 'product_' + product.id,
			code: product.code,
			type: 'product',
			name: product.name,
			price: all_price,
			finish_m: all_finish_m,
			now_num: '-', // 总体 now_num 不在这层处理
			require: '-',
			children: children_list
		})
	}
	merge_process_list()
}
const car_popup_Show = ref(true)
function numChange(e, row) {
	row.f_num = e.value * row.bom_num
	for (let i = 0; i < process_list.value.length; i++) {
		const record = process_list.value[i]
		if (record.code === row.code) {
			// 设置所有子工序的 now_num 为 row.num
			for (let j = 0; j < record.children.length; j++) {
				record.children[j].now_num = e.value
			}
			break // 找到就跳出循环
		}
	}
}


//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('p_plan:refresh')
		}
	})
}

</script>

<style lang="scss" scoped></style>